package com.crimerank;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.crimerank.data.StopCrime;
import com.crimerank.data.ParcelableGeoPoint;
import com.google.android.maps.GeoPoint;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Stops extends BaseListActivity {

	BusStopAdapter m_adapter;
	ArrayList<GeoPoint> points = new ArrayList<GeoPoint>();
	Bundle loc;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stops);

		// Setup the list adapter
		m_adapter = new BusStopAdapter(this, R.layout.stopsrow,
				new ArrayList<StopCrime>());
		setListAdapter(m_adapter);

		// Get lat/long from the Intent extras
		this.loc = getIntent().getExtras().getBundle("loc");
		
		// Request data from server
		double lat = loc.getDouble("lat");
		double lon = loc.getDouble("lon");
		requestData(lat, lon, 10);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent myIntent = new Intent(v.getContext(), StopRoutes.class);
		myIntent.putExtra("StopCrimeObj", m_adapter.getItem(position));
		
		// Send the current location and the "list" of the one stop.
		myIntent.putExtra("loc", loc);
		ArrayList<ParcelableGeoPoint> pointsExtra = new ArrayList<ParcelableGeoPoint>();
		pointsExtra.add(new ParcelableGeoPoint(points.get(position)));
		myIntent.putExtra("points", pointsExtra);
		
		startActivity(myIntent);
	}

	private void requestData(double lat, double lon, int count) {
		try {
			String url = getResources().getString(R.string.URL_NEAREST_BUSSTOP);
			String query = String.format("lat=%s&lon=%s&count=%s",
					URLEncoder.encode(Double.toString(lat), "UTF-8"),
					URLEncoder.encode(Double.toString(lon), "UTF-8"),
					URLEncoder.encode(Integer.toString(count), "UTF-8"));

			// Perform the HTTP request
			String result = doHttpRequest(url, query);

			// Process results and display list
			processJson(result);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public void processJson(String str) throws JSONException {
		m_adapter.clear();
		points.clear();

		// Loop thru JSON array and parse out bus stops
		JSONArray ja = new JSONArray(str);
		for (int i = 0; i < ja.length(); i++) {
			
			// Get stop crime data
			JSONObject jo = (JSONObject) ja.get(i);
			StopCrime stopCrime = new StopCrime();
			stopCrime.setCrimeAggregate(jo.getString("crimeAggregate"));
			stopCrime.setTotal(jo.getInt("total"));
			stopCrime.setDistance(jo.getInt("distance"));

			// Get bus stop data
			// BusStop stop = new BusStop();
			JSONObject tmp = jo.getJSONObject("busStop");
			stopCrime.setName(tmp.getString("name"));
			stopCrime.setLocation(tmp.getString("location"));
			stopCrime.setStop_id(Integer.toString(tmp.getInt("stop_id")));
			stopCrime.setGid(tmp.getInt("gid"));
			stopCrime.setRail(false);
			JSONArray ra = tmp.getJSONArray("routes");
			for (int j = 0; j < ra.length(); j++) {
				stopCrime.addRoute(ra.getString(j));
			}

			points.add(stopCrime.getLocation());

			// Add bus stop crime data to list
			m_adapter.add(stopCrime);
		}
	}

	private class BusStopAdapter extends ArrayAdapter<StopCrime> {

		private ArrayList<StopCrime> items;

		public BusStopAdapter(Context context, int textViewResourceId,
				ArrayList<StopCrime> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.stopsrow, null);
			}

			StopCrime stop = items.get(position);

			if (stop != null) {
				TextView textName = (TextView) view.findViewById(R.id.stopName);
				TextView textRoutes = (TextView) view
						.findViewById(R.id.stopRoutes);
				TextView textDist = (TextView) view.findViewById(R.id.stopDist);
				TextView textRank = (TextView) view.findViewById(R.id.stopRank);

				if (textRoutes != null && textName != null && textDist != null
						&& textRank != null) {
					textName.setText(stop.getName());
					textRoutes.setText(stop.getRoutes().toString());
					String str = String.format("(%1.2f mi)",
							stop.getDistance() * 0.000621371192);
					textDist.setText(str);
					textRank.setText("Rank: " + stop.getRank());
				}
			}

			return view;
		}
	}

	public void onClick(View v) {
		Intent myIntent;
		switch (v.getId()) {
		case (R.id.imageMore):
			int nRecords = m_adapter.getCount();
			double lat = loc.getDouble("lat");
			double lon = loc.getDouble("lon");
			requestData(lat, lon, nRecords + 5);
			onContentChanged();
			break;		
		case (R.id.imageMap):
			myIntent = new Intent(v.getContext(), Map.class);
			myIntent.putExtra("loc", loc);

			ArrayList<ParcelableGeoPoint> pointsExtra = new ArrayList<ParcelableGeoPoint>();
			for (GeoPoint point : points) {
				pointsExtra.add(new ParcelableGeoPoint(point));
			}

			myIntent.putExtra("mapType", "geoPoint");
			myIntent.putExtra("points", pointsExtra);
			startActivity(myIntent);
			break;
		case (R.id.imageHome):
			myIntent = new Intent(v.getContext(), Home.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(myIntent);
			break;
		}
	}

}
